package com.example.onlinetaxi.ui.activity.Driver.MainPage.WaitingOrderFragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.onlinetaxi.BaiDuMap.RoutePlan.RoutePlan;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverReceiveOrderThread;
import com.example.onlinetaxi.callback.IExchangeFragments;
import com.example.onlinetaxi.callback.OrderCallBack.BackToGetOrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.BestOrderCallBack;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.dto.OrderDto.CompletedOrderDto;
import com.example.onlinetaxi.dto.OrderDto.OrderDTO;
import com.example.onlinetaxi.ui.activity.DriverToStartPage.DriverToStartActivity;
import com.example.onlinetaxi.ui.activity.RouteInfoPage.RouteInfoActivity;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.TimeUtil;
import com.example.onlinetaxi.view.Dialog.ReceiveOrderDialog;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class GetOrderFragment extends Fragment {

    private View rootView;
    private Button getOrder;

    // 当前activity
    private Activity activity;

    // fragment切换
    private IExchangeFragments iExchangeFragments;
    // 回到自己
    private BackToGetOrderCallBack backToGetOrderCallBack;

    // 请求参数
    private Map<String, String> map = new HashMap<>();
    // 存放显示的order
    private OrderDTO showedOrder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_get_order, container, false);

        getOrder = rootView.findViewById(R.id.driver_begin_receive_order_btn);

        activity = getActivity();

        intiEvent();

        return rootView;
    }

    private void intiEvent() {
        getOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LocalStorage.currentOrder != null) {
                    Toast.makeText(activity, "您当前已经存在一个订单！", Toast.LENGTH_SHORT).show();
                } else {
                    // 切换到取消叫车fragment
                    iExchangeFragments.exchangeFragment();

                    // 向后台发送接单申请
                    sendGetOrderRequest();

                    Toast.makeText(activity, "正在为您寻找合适的订单~", Toast.LENGTH_SHORT).show();

                    // 启动寻找订单线程
                    DriverReceiveOrderThread.finished = false;
                    DriverReceiveOrderThread.bestOrderCallBack = new BestOrderCallBack() {
                        @Override
                        public void bestOrderCallback(OrderDTO orderDTO) {
                            // 弹出提示框,根据订单信息生成界面
                            showDialog(orderDTO);

                            // 取消获取订单
                            backToGetOrderCallBack.backToGetOrder();

                            Looper.loop();
                        }
                    };

                    // 初始化线程
                    DriverReceiveOrderThread.GetPendingOrder getPendingOrder = new DriverReceiveOrderThread.GetPendingOrder(activity, null);
                    DriverReceiveOrderThread.thread = new Thread(getPendingOrder);
                    DriverReceiveOrderThread.thread.start();

                }
            }
        });
    }

    private void showDialog(OrderDTO order) {
        showedOrder = order;

        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 无操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 发送后台消息
                map.clear();
                map.put("phone", LocalStorage.phone);
                map.put("orderId", order.getId().toString());

                // 发出接单请求
                String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "receiveOrder");
                DataResponse dataResponse = GetDataResponse.getDataResponse(response);

                if (dataResponse.getCode().equals("200")) {
                    // 司机接单成功提示
                    Toast.makeText(activity, "接单成功!请尽快前往出发点!", Toast.LENGTH_SHORT).show();

                    map.clear();
                    map.put("orderId", LocalStorage.currentOrderId);

                    // 获取订单
                    String responseStr = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "getReceivedOrder");

                    DataResponse dataResponse2 = GetDataResponse.getDataResponse(responseStr);

                    // 配置合适订单
                    Gson gson = new Gson();
                    LocalStorage.currentOrder = gson.fromJson(dataResponse2.getData().get("order").toString(), CompletedOrderDto.class);
                    // 转换时间格式
                    LocalStorage.currentOrder = TimeUtil.setRightTimeFormat(LocalStorage.currentOrder);
                    // 设置当前订单
                    LocalStorage.currentOrderId = LocalStorage.currentOrder.getId().toString();

                    // 找到路线
                    RoutePlan.findRoute();

                    // 切换到前去接客界面
                    Intent intent = new Intent(activity, DriverToStartActivity.class);
                    activity.startActivity(intent);
                } else {
                    Toast.makeText(activity, "接单失败：" + dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
                }
            }
        };

        View.OnClickListener changeOrderClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 司机拒绝接收次订单，下次叫单不会再出现
                map.clear();

                Toast.makeText(activity, "换一单", Toast.LENGTH_SHORT).show();
                // 标记取消订单
                changeBestOrder();

                // 切换到取消叫车fragment
                iExchangeFragments.exchangeFragment();

                // 向后台发送接单申请
                sendGetOrderRequest();

                Toast.makeText(activity, "正在为您寻找合适的订单~", Toast.LENGTH_SHORT).show();

                // 启动寻找订单线程
                DriverReceiveOrderThread.finished = false;
                DriverReceiveOrderThread.bestOrderCallBack = new BestOrderCallBack() {
                    @Override
                    public void bestOrderCallback(OrderDTO orderDTO) {
                        // 弹出提示框,根据订单信息生成界面
                        showDialog(orderDTO);

                        // 取消获取订单
                        backToGetOrderCallBack.backToGetOrder();

                        Looper.loop();
                    }
                };

                // 初始化线程
                DriverReceiveOrderThread.GetPendingOrder getPendingOrder = new DriverReceiveOrderThread.GetPendingOrder(activity, null);
                DriverReceiveOrderThread.thread = new Thread(getPendingOrder);
                DriverReceiveOrderThread.thread.start();
            }
        };

        View.OnClickListener routeInfoOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置绘图点
                RoutePlan.startMap.put("city", order.getStartCity());
                RoutePlan.startMap.put("place", order.getStartInfo());
                RoutePlan.endMap.put("city", order.getEndCity());
                RoutePlan.endMap.put("place", order.getEndInfo());

                // 跳转到订单对应的等待页面
                Intent intent = new Intent(getActivity(), RouteInfoActivity.class);
                // 传递参数（当前等待秒数）
                Bundle bundle = new Bundle();
                bundle.putString("intentType", "3");
                // 添加信息
                intent.putExtras(bundle);
                startActivity(intent);
            }
        };

        // 显示提示框
        ReceiveOrderDialog.showInfoDialog(
                activity,
                order,
                onCancelClickListener,
                onConfirmClickListener,
                changeOrderClickListener,
                routeInfoOnClickListener
        );
    }

    private void changeBestOrder() {
        map.clear();
        map.put("phone", LocalStorage.phone);
        map.put("orderId", showedOrder.getId().toString());

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "changeBestOrder");
    }

    private void sendGetOrderRequest() {
        map.clear();

        map.put("phone", LocalStorage.phone);
        // 进入接单模式
        map.put("state", "1");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "driver", "changeGetOrderState");
    }

    public void setiExchangeFragments(IExchangeFragments iExchangeFragments) {
        this.iExchangeFragments = iExchangeFragments;
    }

    public void setBackToGetOrderCallBack(BackToGetOrderCallBack backToGetOrderCallBack) {
        this.backToGetOrderCallBack = backToGetOrderCallBack;
    }
}